import {_decorator, Node, Component} from "cc"
import {audios} from "db://assets/script/utils/audioUtils";
import {oops} from "db://oops-framework/core/Oops";
import {UIID} from "db://assets/script/game/common/config/gameUiConfig";
import {smc} from "db://assets/script/game/common/singletonModuleComp";
import {Server} from "db://assets/script/network/ws/server";
import {maxReconnectAttempts} from "db://assets/script/game/constants/common";
import {Player} from "db://assets/script/game/player/player";
import {pb} from "db://assets/script/network/ws/proto";
import {ReconnectComp} from "db://assets/script/game/initialize/comp/reconnectComp";

const {ccclass, property} = _decorator

@ccclass("LoginViewComp")
export class LoginViewComp extends Component {

    @property({
        type: Node,
        tooltip: "登录按钮"
    })
    loginPanel: Node = null!

    async loginByTourist() {
        // 从 url 地址获取 touristId, 如 http://localhost:7456/?id=demo
        // console.log(window.location.search, window.location.href, "URLSearchParams", searchParams.has("id"), searchParams.get("id"))
        const searchParams = new URLSearchParams(window.location.search);
        let touristId = 'demo'
        if (searchParams.has('id')) {
            touristId = searchParams.get('id')
        }
        // 禁止点击登录
        this.loginPanel.active = false
        audios.btnClick()
        // 加载动画
        await oops.gui.openAsync(UIID.netinstable)
        // 重新登录
        // 连接 server
        Server.init("localhost", 12345, "/", maxReconnectAttempts, () => {
            // 界面跳出来以后，再登录，否则loading界面有可能删不掉
            Player.loginByTourist(touristId,  (resp: pb.IPlayerModel) => {
                // 打开大厅界面
                Player.getInstance().updatePlayerInfo(resp)
                oops.gui.remove(UIID.netinstable)
                oops.gui.remove(UIID.login)
                if (smc.initialize.isLogin && smc.initialize.reconnect) {
                    // 断线重连， 检查是否有未完成房间
                    smc.dating.restoreDesk(true)
                    // 重置状态
                    smc.initialize.reconnect = false
                } else {
                    // 第一次登录
                    oops.gui.open(UIID.dating)
                }
                smc.initialize.isLogin = true
            })
        })
        // 监听网络
        smc.initialize.add(ReconnectComp)
    }
}